import React, { useState } from "react"
import { useHistory } from 'react-router-dom'
import {
  Box,
  Input,
  InputGroup,
  Stack,
  InputLeftAddon,
  Button,
  FormControl,
  Text,
  Link,
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverArrow,
  PopoverBody,
  useToast
} from "@chakra-ui/react"
import { FaUserAlt, FaLock, FaMobileAlt, FaExclamationTriangle } from "react-icons/fa"
import { Formik, Form, Field } from "formik"
import axios from "axios"
import * as Yup from "yup"

export default function SignUp() {
  const toast = useToast()
  const history = useHistory()
  const [isLoading, setIsLoading] = useState(false)
  const initialValues = {
    username: '',
    email: '',
    password: ''
  }

  const handleSubmit = values => {
    setIsLoading(true)
    axios.post('https://conduit.productionready.io/api/users', {
      user: {
        ...values
      }
    }).then(res => {
      setIsLoading(false)
      if (res.status === 200) {
        toast({
          title: '注册成功',
          status: 'success',
          position: 'top',
          isClosable: true
        })
        history.push('/sign_in')
      }
    }).catch(err => {
      setIsLoading(false)
      err && toast({
        title: '注册失败，请重试',
        status: 'error',
        position: 'top',
        isClosable: true,
      })
    })
  }

  const schema = Yup.object({
    username: Yup.string()
      .max(8, "昵称的长度不能大于8")
      .required("请输入昵称"),
    email: Yup.string()
      .email('输入的邮箱格式不正确')
      .max(32, "邮箱的长度不能大于32")
      .required("请输入邮箱"),
    password: Yup.string()
      .min(8, "密码的长度不能小于8位")
      .max(20, "密码的长度不能大于20")
      .required("请输入密码"),
  })

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={schema}
    >
      {props => (
        <Form>
          <Stack spacing="4" w="100%">
            <Stack spacing="0" w="100%">
              <Field name="username">
                {({ field, form }) => (
                  <FormControl>
                    <Popover
                      autoFocus={false}
                      returnFocusOnClose={false}
                      isOpen={form.errors.username && form.touched.username}
                      placement="right"
                      closeOnBlur={false}
                    >
                      <InputGroup bgColor="#F7F7F7">
                        <InputLeftAddon
                          children={<FaUserAlt />}
                          color="#969696"
                          borderBottom="none"
                          bg="none"
                          borderColor="#c8c8c8"
                          borderBottomLeftRadius="0"
                        />
                        <Input
                          {...field}
                          placeholder="你的昵称"
                          borderBottom="none"
                          borderLeft="none"
                          bg="none"
                          fontSize="14px"
                          paddingLeft="0"
                          borderColor="#c8c8c8"
                          borderBottomRightRadius="0"
                          _placeholder={{ color: "#969696" }}
                          _focus={{ boxShadow: "none" }}
                          onBlur={form.handleBlur}
                        />
                        <PopoverTrigger><Box></Box></PopoverTrigger>
                      </InputGroup>
                      <PopoverContent borderColor="#ea6f5a">
                        <PopoverArrow border="1px solid #ea6f5a" borderRight="none" borderTop="none" />
                        <PopoverBody>
                          <Stack direction="horizontal" align="center">
                            <FaExclamationTriangle color="#ea6f5a" />
                            <Text fontSize="14px" ml="5px">{form.errors.username}</Text>
                            <Text fontSize="14px" ml="5px">{form.touched.username}</Text>
                          </Stack>
                        </PopoverBody>
                      </PopoverContent>
                    </Popover>
                  </FormControl>
                )}
              </Field>
              <Field name="email">
                {({ field, form }) => (
                  <FormControl>
                    <Popover
                      autoFocus={false}
                      returnFocusOnClose={false}
                      isOpen={form.errors.email && form.touched.email}
                      placement="right"
                      closeOnBlur={false}
                    >
                      <InputGroup bgColor="#F7F7F7">
                        <InputLeftAddon
                          children={<FaMobileAlt />}
                          color="#969696"
                          borderBottom="none"
                          bg="none"
                          borderColor="#c8c8c8"
                          borderTopLeftRadius="0"
                          borderBottomLeftRadius="0"
                        />
                        <Input
                          {...field}
                          placeholder="邮箱"
                          borderBottom="none"
                          borderLeft="none"
                          bg="none"
                          fontSize="14px"
                          paddingLeft="0"
                          borderColor="#c8c8c8"
                          borderTopRightRadius="0"
                          borderBottomRightRadius="0"
                          _placeholder={{ color: "#969696" }}
                          _focus={{ boxShadow: "none" }}
                          onBlur={form.handleBlur}
                        />
                        <PopoverTrigger><Box></Box></PopoverTrigger>
                      </InputGroup>
                      <PopoverContent borderColor="#ea6f5a">
                        <PopoverArrow border="1px solid #ea6f5a" borderRight="none" borderTop="none" />
                        <PopoverBody>
                          <Stack direction="horizontal" align="center">
                            <FaExclamationTriangle color="#ea6f5a" />
                            <Text fontSize="14px" ml="5px">{form.errors.email}</Text>
                          </Stack>
                        </PopoverBody>
                      </PopoverContent>
                    </Popover>
                  </FormControl>
                )}
              </Field>
              <Field name="password">
                {({ field, form }) => (
                  <FormControl mb="10px">
                    <Popover
                      autoFocus={false}
                      returnFocusOnClose={false}
                      isOpen={form.errors.password && form.touched.password}
                      placement="right"
                      closeOnBlur={false}
                    >
                      <InputGroup bgColor="#F7F7F7">
                        <InputLeftAddon
                          children={<FaLock />}
                          color="#969696"
                          bg="none"
                          borderColor="#c8c8c8"
                          borderTopLeftRadius="0"
                        />
                        <Input
                          {...field}
                          type="password"
                          placeholder="设置密码"
                          autoComplete="new-password"
                          borderLeft="none"
                          bg="none"
                          fontSize="14px"
                          paddingLeft="0"
                          borderTopRightRadius="0"
                          borderColor="#c8c8c8"
                          _placeholder={{ color: "#969696" }}
                          _focus={{ boxShadow: "none" }}
                          onBlur={form.handleBlur}
                        />
                        <PopoverTrigger><Box></Box></PopoverTrigger>
                      </InputGroup>
                      <PopoverContent borderColor="#ea6f5a">
                        <PopoverArrow border="1px solid #ea6f5a" borderRight="none" borderTop="none" />
                        <PopoverBody>
                          <Stack direction="horizontal" align="center">
                            <FaExclamationTriangle color="#ea6f5a" />
                            <Text fontSize="14px" ml="5px">{form.errors.password}</Text>
                          </Stack>
                        </PopoverBody>
                      </PopoverContent>
                    </Popover>
                  </FormControl>
                )}
              </Field>
            </Stack>
            <Button
              type="submit"
              w="100%"
              color="#fff"
              bgColor="#42c02e"
              borderRadius="25px"
              _hover={{ bgColor: "#3db922" }}
              _focus={{ boxShadow: "none" }}
              isLoading={isLoading}
              loadingText="注册中..."
            >
              注册
            </Button>
            <Stack w="100%" spacing="1" fontSize="12px">
              <Text w="100%" textAlign="center">点击 “注册” 即表示您同意并愿意遵守简书</Text>
              <Text w="100%" textAlign="center"><Link href="http://www.jianshu.com/p/c44d171298ce" isExternal color="#3194d0">用户协议</Link>和<Link href="http://www.jianshu.com/p/2ov8x3" isExternal color="#3194d0">隐私政策</Link></Text>
            </Stack>
          </Stack>
        </Form>
      )
    }
    </Formik>
  );
}
